package com.cs410.collabwriting.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class DictionaryWebService
 */
@WebServlet("/dictionary")
public class DictionaryWebService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DictionaryWebService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * Uses a dictionary web service from : http://services.aonaware.com/DictService/DictService.asmx/Define?word=
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String word = request.getParameter("word");
		 URL dict = new URL("http://services.aonaware.com/DictService/DictService.asmx/Define?word=" + word);
	        URLConnection yc = dict.openConnection();
	        BufferedReader in = new BufferedReader(
	                                new InputStreamReader(
	                                yc.getInputStream()));
	        String inputLine = " ";
	        StringBuffer buf = new StringBuffer();

	        while (inputLine != null) {
	        	inputLine = in.readLine();
	        	buf.append( inputLine );
	        }
	        in.close();
	        JSONObject json = new JSONObject();
	       
	        try {
	        	json.put("definition", buf.toString());
	        } catch (JSONException e) {
					
	        }
			
	        response.getWriter().print( json.toString() );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
